package common.commands;

import common.AltaRicaModel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import parser.AltaRicaParseModel;
import parser.AltaRicaParser;
import parser.AltaRicaParseNode.CycleDetectionException;
import ui.gui.documents.AbstractDocument;
import ui.gui.documents.EditorFactory;
import ui.gui.documents.toolbox.AltaricaExplorer;
import ui.gui.documents.toolbox.Workspace;

public class LoadAltaRicaModel implements ICommand {

	@Override
	public String getName() {

		return "load";
	}

	@Override
	public String getSynopsis() {

		return "load <file.alt>";
	}

	@Override
	public CommandValue run(String arg) {

		FileInputStream fileIn = null;

		try {
			fileIn = new FileInputStream(arg);
		} catch (FileNotFoundException e) {

			System.out.println("Unable to open file " + arg);
			return CommandValue.KO;
		}

		try {
			AbstractDocument document = EditorFactory.getInstance()
					.createFromFile(new File(arg));
			Workspace.getInstance().AddDocument(document);

			if (arg.endsWith(".alt")) {
				AltaRicaParseModel pmodel = AltaRicaParser.parseModel(arg,
						fileIn);
				pmodel.addAlatricaModelListener(AltaricaExplorer.getInstance());

				try {
					fileIn.close();
				} catch (IOException e) {
					System.out.println("Error: unable to close the file: "
							+ arg);
				}

				try {
					AltaRicaModel.compileFromAST(pmodel, true);
					System.out.println("Model loaded");

					return CommandValue.OK;
				} catch (CycleDetectionException exception) {
					System.out.println(exception.getMessage());
				}
			} else {
				System.out.println("File added to workspace");
				return CommandValue.OK;
			}

		} catch (Exception exception) {
			AbstractDocument document = EditorFactory.getInstance()
					.createFromFile(new File(arg));
			Workspace.getInstance().AddDocument(document);
			System.out.println("Unable to parse file [" + arg + "]");
		}

		return CommandValue.KO;

	}

	@Override
	public String help() {

		return "Loads and parse an AltaRica model or add a plain text file to workspace";
	}
}
